package com.jianyun.jyzs.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.adapter.CrmAttachmentAdapter;
import com.jianyun.jyzs.bean.AttachmentInfo;
import com.jianyun.jyzs.bean.CrmDetial;
import com.jianyun.jyzs.bean.CrmSearchBean;
import com.jianyun.jyzs.bean.NewCreateCrmBean;
import com.jianyun.jyzs.constant.SysConstant;
import com.jianyun.jyzs.dao.CrmDao;
import com.jianyun.jyzs.http.CreateCrmHelper;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.widget.FullyLinearLayoutManager;
import com.jianyun.jyzs.widget.LoadingDialog;
import com.jianyun.jyzs.widget.voice.AudioRecorderButton;
import com.jrmf360.rylib.common.util.ToastUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import com.jianyun.jyzs.utils.RceLog;

/**
 * 创建CRM
 * Created by yangshijun on 2018/6/4.
 */

public class CreateCrmActivity extends AppCompatActivity implements CreateCrmHelper.CrmCreateListener {
    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.tv_checked)
    TextView tvCheck;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.iv_moreLinearLayout)
    LinearLayout ivMoreLinearLayout;
    @BindView(R.id.topCreat)
    LinearLayout topCreat;
    @BindView(R.id.iv_single)
    ImageView ivSingle;
    @BindView(R.id.iv_group)
    ImageView ivGroup;
    @BindView(R.id.topChatDetail)
    LinearLayout topChatDetail;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.titleName)
    EditText titleName;
    @BindView(R.id.entNature)
    TextView entNature;
    @BindView(R.id.entNatureSelect)
    ImageView entNatureSelect;
    @BindView(R.id.linearLayout1)
    LinearLayout linearLayout1;
    @BindView(R.id.industry)
    TextView industryTv;
    @BindView(R.id.industrySelect)
    ImageView industrySelect;
    @BindView(R.id.linearLayout2)
    LinearLayout linearLayout2;
    @BindView(R.id.regCapital)
    EditText regCapital;
    @BindView(R.id.textView6)
    TextView textView6;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.addressSelect)
    ImageView addressSelect;
    @BindView(R.id.linearLayout3)
    LinearLayout linearLayout3;
    @BindView(R.id.detialaddress)
    EditText detialaddress;
    @BindView(R.id.linearLayout4)
    LinearLayout linearLayout4;
    @BindView(R.id.enclosureList)
    RecyclerView recyclerView;
    @BindView(R.id.iv_ll_enclosure)
    ImageView ivLlEnclosure;
    @BindView(R.id.tv_ll_enclosure)
    TextView tvLlEnclosure;
    @BindView(R.id.ll_enclosure)
    LinearLayout llEnclosure;
    @BindView(R.id.btn_take_picture)
    ImageView btnTakePicture;
    @BindView(R.id.btn_picture)
    ImageView btnPicture;
    @BindView(R.id.btn_voice)
    AudioRecorderButton btnVoice;
    @BindView(R.id.btn_video)
    ImageView btnVideo;
    @BindView(R.id.btn_file)
    ImageView btnFile;
    @BindView(R.id.ll_mediaBase)
    LinearLayout llMediaBase;
    @BindView(R.id.order_layoutId)
    LinearLayout orderLayoutId;
    @BindView(R.id.scrollViewId)
    ScrollView scrollViewId;


    private CreateCrmHelper helper;
    private String enid;//企业性质
    private String industry;
    private double lat = 100;
    private double lng = 100;
    private CrmDao crmDao;
    private LoadingDialog loadingDialog;
    public File cameraFile;//保存相机获取照片
    private CrmAttachmentAdapter attachmentAdapter;
    private String enNatureTV_arg;
    private String industryTV_arg;
    private String enterpriseCode;
    private String name;
    private String userId;
    private String[] permisson = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
    private static final int GET_ENNATURE = 100;
    private static final int GET_INDUSTRY = 101;
    private static final int GET_LOCATION = 102;
    private static final int LOCATION_PERMISSON = 103;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crm_create);
        ButterKnife.bind(this);
        initData();
        initView();
    }

    private void initData() {
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        name = LoginCache.getInstance().getUserDetaileInfo().getName();
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        loadingDialog = LoadingDialog
                .create(this)
                .setDetailLabel("正在创建crm");
        crmDao = new CrmDao(this);
        attachmentAdapter = new CrmAttachmentAdapter(this, null);
        helper = new CreateCrmHelper(userId, name, enterpriseCode, attachmentAdapter, this, this);
        helper.handAttr(llMediaBase);
        helper.setUploadAttachmentListener(new CreateCrmHelper.UploadAttachmentListener() {
            @Override
            public void uploadCount(int count) {
                RceLog.d("lml", "上传附件__count=" + count);
                if (count == 0) {
                    loadingDialog.dismiss();
                    ToastUtil.showNoWaitToast(CreateCrmActivity.this, "创建成功");
                    finish();
                }
            }
        });
    }

    private void initView() {
        topBack.setVisibility(View.VISIBLE);
        topText.setVisibility(View.VISIBLE);
        tvCheck.setVisibility(View.VISIBLE);
        topText.setText("创建我的客户");
        tvCheck.setText("保存");
        tvCheck.setTextColor(getResources().getColor(R.color.color_primary));
        recyclerView.setLayoutManager(new FullyLinearLayoutManager(this));
        recyclerView.setAdapter(attachmentAdapter);
    }

    @OnClick({R.id.topBack, R.id.tv_checked, R.id.linearLayout1, R.id.linearLayout2, R.id.linearLayout3, R.id.ll_enclosure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.topBack:
                finish();
                break;
            case R.id.linearLayout1:
                startActivityForResult(new Intent(this, EntNatureActivity.class), GET_ENNATURE);
                break;
            case R.id.linearLayout2:
                startActivityForResult(new Intent(this, IndustryActivity.class), GET_INDUSTRY);
                break;
            case R.id.linearLayout3:
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    startActivityForResult(new Intent(this, CrmMapLocationActivity.class), GET_LOCATION);
                } else {
                    ActivityCompat.requestPermissions(this, permisson, LOCATION_PERMISSON);
                }
                break;
            case R.id.ll_enclosure:
                if (llMediaBase.getVisibility() == View.GONE) {
                    ivLlEnclosure.setImageDrawable(getResources().getDrawable(R.drawable.ic_enclosure_close));
                    tvLlEnclosure.setTextColor(getResources().getColor(R.color.red));
                    llMediaBase.setVisibility(View.VISIBLE);
                } else {
                    ivLlEnclosure.setImageDrawable(getResources().getDrawable(R.drawable.ic_enclosure_open));
                    tvLlEnclosure.setTextColor(getResources().getColor(R.color.blue));
                    llMediaBase.setVisibility(View.GONE);
                }
                break;
            case R.id.tv_checked:
                String t1 = titleName.getText().toString().trim();
                if (TextUtils.isEmpty(t1)) {
                    ToastUtil.showNoWaitToast(this, "请输入客户名称");
                    return;
                }
                String t2 = entNature.getText().toString().trim();
                if (TextUtils.isEmpty(t2)) {
                    ToastUtil.showNoWaitToast(this, "请选择企业性质");
                    return;
                }
                String t3 = industryTv.getText().toString().trim();
                if (TextUtils.isEmpty(t3)) {
                    ToastUtil.showNoWaitToast(this, "请选择所属行业");
                    return;
                }
                String t4 = regCapital.getText().toString().trim();
                if (TextUtils.isEmpty(t4)) {
                    ToastUtil.showNoWaitToast(this, "请填写注册资本");
                    return;
                }
                String t5 = address.getText().toString().trim();
                if (TextUtils.isEmpty(t5)) {
                    ToastUtil.showNoWaitToast(this, "请选择企业地址");
                    return;
                }
                String t6 = detialaddress.getText().toString().trim();
                if (TextUtils.isEmpty(t6)) {
                    ToastUtil.showNoWaitToast(this, "请输入详细地址");
                    return;
                }

                String nameCanpeny = "";
                String createUserName = "";
                String property = "";
                String industry = "";
                String addressStr = "";
                String detaileAdrress="";
                try {
                    nameCanpeny = URLEncoder.encode(titleName.getText().toString(), "utf-8");
                    createUserName = URLEncoder.encode(name, "utf-8");
                    property = URLEncoder.encode(enNatureTV_arg, "utf-8");
                    industry = URLEncoder.encode(industryTV_arg, "utf-8");
                    addressStr = URLEncoder.encode(address.getText().toString(), "utf-8");
                    detaileAdrress=URLEncoder.encode(t6,"utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                HashMap<String, String> map = new HashMap<>();
                map.put("method", "crm_create");
                map.put("userId", userId);
                map.put("enterpriseCode", enterpriseCode);
                map.put("name", nameCanpeny);
                map.put("createUserId", userId);
                map.put("createUserName", createUserName);
                map.put("property", property);
                map.put("industry", industry);
                map.put("capital", regCapital.getText().toString());
                map.put("address", detaileAdrress+addressStr);
                map.put("lng", lat + "");
                map.put("lat", lng + "");
                map.put("appCode","jyzs");
                map.put("appType","Android");
                map.put("appVersion","1.0.2");
                Log.i("test", "创建：" + map.toString());
                loadingDialog.show();
                helper.newCreateCrm(map, userId, crmDao);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        helper.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == GET_ENNATURE & data != null) {
                enid = data.getStringExtra(SysConstant.msg_key_string1);
                enNatureTV_arg = data.getStringExtra(SysConstant.msg_key_string2);
                entNature.setText(enNatureTV_arg);
            } else if (requestCode == GET_INDUSTRY & data != null) {
                industry = data.getStringExtra(SysConstant.msg_key_string1);
                industryTV_arg = data.getStringExtra(SysConstant.msg_key_string2);
                industryTv.setText(industryTV_arg);
            } else if (requestCode == GET_LOCATION & data != null) {
                PoiItem poiItem = data.getParcelableExtra(SysConstant.msg_key_parcelable);
                LatLonPoint latLonPoint = poiItem.getLatLonPoint();
                lat = latLonPoint.getLatitude();
                lng = latLonPoint.getLongitude();
                address.setText(poiItem.getTitle());
                detialaddress.setText(poiItem.getProvinceName() + poiItem.getCityName() + poiItem.getAdName() + poiItem.getBusinessArea() + poiItem.getSnippet());
            }
        }
    }

    @Override
    public void createSuccess(NewCreateCrmBean newCreateCrmBean) {
//        List<AttachmentInfo> attachlist = helper.getAttachlist();
//        if (attachlist.size() > 0) {
//            helper.uploadAttachment(attachlist, po);
//        } else {
        loadingDialog.dismiss();
        ToastUtil.showNoWaitToast(this, "创建成功");
        onCretaLisenter.onSuccess();
        //Intent intent = new Intent(this, CrmActivity.class);
        //intent.putExtra(SysConstant.msg_key_parcelable, po);
        // startActivity(intent);
        finish();
//        }
    }

    @Override
    public void createFail(String msg) {
        ToastUtil.showNoWaitToast(this, msg);
        loadingDialog.dismiss();
        onCretaLisenter.onFailed();
    }

    public interface OnCretaCrmLisenter {
        void onSuccess();

        void onFailed();
    }


    private static OnCretaCrmLisenter onCretaLisenter;

    public static void setOnCretaCrmListener(OnCretaCrmLisenter onCretaCrmLisenter) {
        onCretaLisenter = onCretaCrmLisenter;
    }

}
